package flex.cc.uac.service.impl;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import flex.cc.common.utils.JwtUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import eu.bitwalker.useragentutils.UserAgent;
import flex.cc.RedisKeyUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.base.dto.UserTokenDto;
import flex.cc.core.utils.RequestUtil;
import flex.cc.uac.dao.UacUserDao;
import flex.cc.uac.dao.UacUserTokenDao;
import flex.cc.uac.dto.token.TokenMainQueryDto;
import flex.cc.uac.entity.UacUserEntity;
import flex.cc.uac.entity.UacUserTokenEntity;
import flex.cc.uac.enums.UacUserTokenStatusEnum;
import flex.cc.uac.service.UacUserTokenService;


@Service("uacUserTokenService")
@Transactional(rollbackFor = Exception.class)
public class UacUserTokenServiceImpl extends ServiceImpl<UacUserTokenDao, UacUserTokenEntity> implements UacUserTokenService {

    @Resource
    private UacUserDao uacUserDao;
    @Resource
    private UacUserTokenDao uacUserTokenDao;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void saveUserToken(String accessToken, String refreshToken, LoginAuthDto loginAuthDto, HttpServletRequest request) {
        // 获取登录时间
        Long userId = loginAuthDto.getUserId();
        UacUserEntity uacUser = uacUserDao.selectById(userId);
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //获取客户端操作系统
        final String os = userAgent.getOperatingSystem().getName();
        //获取客户端浏览器
        final String browser = userAgent.getBrowser().getName();
        final String remoteAddr = RequestUtil.getRemoteAddr(request);
        // 根据IP获取位置信息
        final String remoteLocation = "";

        // 存入数据库
        UacUserTokenEntity uacUserToken = new UacUserTokenEntity();
        int accessTokenValidateSeconds = 7200;
        uacUserToken.setOs(os);
        uacUserToken.setBrowser(browser);
        uacUserToken.setAccessToken(accessToken);
        uacUserToken.setAccessTokenValidity(accessTokenValidateSeconds);
        uacUserToken.setLoginIp(remoteAddr);
        uacUserToken.setLoginLocation(remoteLocation);
        uacUserToken.setLoginTime(uacUser.getLastLoginTime());
        uacUserToken.setLoginName(loginAuthDto.getLoginName());
        uacUserToken.setRefreshToken(refreshToken);
        //uacUserToken.setRefreshTokenValidity(refreshTokenValiditySeconds);
        uacUserToken.setStatus(UacUserTokenStatusEnum.ON_LINE.getStatus());
        uacUserToken.setUserId(userId);
        uacUserToken.setUserName(loginAuthDto.getUserName());
        uacUserToken.setUpdateInfo(loginAuthDto);
        uacUserToken.setGroupId(loginAuthDto.getGroupId());
        uacUserToken.setGroupName(loginAuthDto.getGroupName());
        uacUserToken.setBelongComCode(loginAuthDto.getBelongComCode());
        uacUserToken.setBelongComName(loginAuthDto.getBelongComName());
        uacUserToken.setComCode(loginAuthDto.getComCode());
        uacUserToken.setComName(loginAuthDto.getComName());
        this.save(uacUserToken);

        UserTokenDto userTokenDto = new ModelMapper().map(uacUserToken, UserTokenDto.class);
        userTokenDto.setUserCode(loginAuthDto.getUserCode());
        // 存入redis数据库
        System.out.println("登录日志：UacUserTokenServiceImpl.saveUserToken - 登录成功，将信息写入redis");
        updateRedisUserToken(accessToken, accessTokenValidateSeconds, userTokenDto);
    }

    private void updateRedisUserToken(String accessToken, int accessTokenValidateSeconds, UserTokenDto userTokenDto) {
        redisTemplate.opsForValue().set(RedisKeyUtil.getAccessTokenKey(accessToken), userTokenDto, accessTokenValidateSeconds, TimeUnit.SECONDS);
    }

	@Override
	public IPage<UacUserTokenEntity> listTokenWithPage(TokenMainQueryDto token) {
		IPage<UacUserTokenEntity> page = new Page<UacUserTokenEntity>(token.getPageNum(),token.getPageSize());
		page = uacUserTokenDao.selectTokenList(page,token);
		return page;
	}
}